import { ref } from "vue";
import { defineStore } from "pinia";
import { loginAPI } from "@/apis/user";
import { useCartStore } from "./cartStore";
import { mergeCartAPI } from "@/apis/cart";

export const useUserStore = defineStore(
    "user",
    () => {
        // 获取购物车信息
        const cartStore = useCartStore();

        // state 用户数据
        const userInfo = ref({});

        // action 获取用户数据
        const getUserInfo = async ({ account, password }) => {
            const res = await loginAPI({ account, password });
            userInfo.value = res.result;

            // 合并购物车操作
            mergeCartAPI(
                cartStore.cartList.map((item) => {
                    return {
                        skuId: item.skuId,
                        selected: item.selected,
                        count: item.count,
                    };
                })
            );

            // 获取最新的购物车列表
            cartStore.updateNewList();
        };

        // action 清除用户信息
        const clearUserInfo = () => {
            userInfo.value = {};
            // 清除用户购物车数据
            cartStore.clearCart();
        };

        // 以对象的格式将state、action return
        return {
            userInfo,
            getUserInfo,
            clearUserInfo,
        };
    },
    { persist: true }
);
